package action.test;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import tool.ImageCut;
import util.TimeTest;

public class UploadImage {
	private File pic;
	private String picFileName;
	private String picUrl;
	
	private int x;
	private int y;
	// ===剪切点宽度
	private int width;
	private int height;
	
	public String execute(){
		return "success";
	}
		
	public String uploadPic(){
		TimeTest tt = new TimeTest();
		
		String sti = tt.getFNowTime("yyyy-MM-dd HH:mm:ss");
		System.out.println(sti);
		String picname=sti + picFileName;
		String savedir="/data/uploadimage";
		picUrl=".."+savedir+"/"+picname;
		
		String[] str = { ".jpg", ".jpeg", ".bmp", ".gif" };  
        // 限定文件大小是4MB  
        if (pic == null || pic.length() > 41943004) {  
            return "error";  
        }  
        //for (String s : str) {  
           // if (picFileName.endsWith(s)) {  
                String realPath = ServletActionContext.getServletContext().getRealPath(savedir);
                File saveFile = new File(new File(realPath), picname); // 在该实际路径下实例化一个文件  
                // 判断父目录是否存在  
                if (!saveFile.getParentFile().exists()) {  
                    saveFile.getParentFile().mkdirs();  
                }  
                try {  
                    FileUtils.copyFile(pic, saveFile); 
                } catch (IOException e) {  
                    return "imageError";  
                }  
            //}  
        //}  
		return "success";
	}

	public void cutPic(){
		String pathfrom = ServletActionContext.getServletContext().getRealPath("/data/uploadimage/123.jpg");
		String pathto=ServletActionContext.getServletContext().getRealPath("/data/uploadimage/new_123.jpg");
		ImageCut img=new ImageCut();
		img.setArea(x, y, width, height);
		img.setPath(pathfrom, pathto);
		try {
			img.cut();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public File getPic() {
		return pic;
	}

	public void setPic(File pic) {
		this.pic = pic;
	}

	public String getPicFileName() {
		return picFileName;
	}

	public void setPicFileName(String picFileName) {
		this.picFileName = picFileName;
	}

	public String getPicUrl() {
		return picUrl;
	}

	public void setPicUrl(String picUrl) {
		this.picUrl = picUrl;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}
}
